/*
 * @Author: 1243sd 782012816@qq.com
 * @Date: 2024-03-11 20:55:36
 * @LastEditors: 1243sd 782012816@qq.com
 * @LastEditTime: 2024-06-26 22:54:36
 * @FilePath: \ykt_admin\src\store\modules\user.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { login, getUserInfo, getUserPermisson } from '@/api/requestApi/logins'
import router from '@/router/modules/goodsRouter'

const getDefaultState = () => {
  return {
    permission: localStorage.getItem('permission'), // 获取存储本地动态路由
    isAddRoutes: false, // 记录是否添加过路由
    get_Token() { // 获取token
      return localStorage.getItem('token')
    },
  }
}

const state = getDefaultState()

const mutations = {
  // 添加路由  
  ADD_PERMISSION(state, permission) {
    state.permission = JSON.stringify(permission)
    localStorage.setItem('permission', JSON.stringify(permission))
  },
  // 是否添加路由
  IS_ADD_ROUTES(state, DATA) {
    state.isAddRoutes = DATA
    localStorage.setItem("isAddRoutes",DATA)
  },
}

const actions = {
  // 是否添加过路由
  SET_IS_ADD_ROUTES({ commit }, data) {
    commit('IS_ADD_ROUTES', data)
  },
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo).then(response => {
        localStorage.setItem('token', response.token)
        localStorage.setItem('username', userInfo.username)
        // getUserInfo().then(res => {
        //   let arr = res.roles[0].permissions.map(item => item.id)
        //   localStorage.setItem('p', JSON.stringify(res))
        //   commit('ADD_PERMISSION', arr) // 设置权限
          
        //   localStorage.setItem('username', res.username)
        //   localStorage.setItem('userInfo', res)
        //   resolve(arr.findIndex(item => item == 18) != -1? '/' : router.find(item => item.meta.permission == arr[0]).path)
        console.log(response,'response');
        resolve('/')
        // })
      })
      //   localStorage.setItem('username', response.username)
      //   localStorage.setItem('userId', response.userId)
        // localStorage.setItem('token', '12321')
        
      //   resolve(response)
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

